<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ classroom.course_name }} - {{ classroom.class_name }}</title>
    <link rel="stylesheet" href="/static/css/classroom_main_v4.css">
    <link rel="stylesheet" href="/static/css/ai_chat.css">

    <script src="/static/js/marked.min.js"></script>
    <script src="/static/js/tools.js"></script>

</head>
<body>
    <div class="page-header">
        <div class="breadcrumbs">
            <h1>
                <a href="/dashboard">我的仪表盘</a> &gt; {{ classroom.course_name }} ({{ classroom.class_name }})
            </h1>
        </div>
        <div class="user-info">
            欢迎, <strong>{{ user_info.name }}</strong>（{{ user_info.nickname if user_info.nickname else '学生' }}）
            <a href="/logout">退出登录</a>
        </div>
    </div>

    <div class="main-container">
        <div class="panel content-panel">
            <div class="assignments-panel">
                <div class="panel-header">
                    <h2>{% if user_info.role == 'teacher' %}作业管理{% else %}我的作业{% endif %}</h2>
                    {% if user_info.role == 'teacher' %}
                    <button class="button primary-button" onclick="openAssignmentModal()">+ 新建作业</button>
                    {% endif %}
                </div>
                <div class="panel-content">
                    <div class="assignments-grid">
                        {% for assignment in assignments %}
                        <div class="assignment-card" onclick="location.href='/assignment/{{ assignment.id }}'">
                            <h3>{{ assignment.title }}</h3>
                            {% if user_info.role == 'teacher' %}
                                <span class="status-badge status-{{ assignment.status }}">
                                    {{ {'new': '草稿', 'published': '已发布'}[assignment.status] }}
                                </span>
                            {% else %}
                                {% if assignment.submission_status == 'unsubmitted' %}
                                    <span class="status-badge status-unsubmitted">未提交</span>
                                {% elif assignment.submission_status == 'submitted' %}
                                    <span class="status-badge status-submitted">已提交</span>
                                {% elif assignment.submission_status == 'grading' %}
                                    <span class="status-badge status-grading">批改中</span>
                                {% elif assignment.submission_status == 'graded' %}
                                    <span class="status-badge status-graded">已批改 ({{ assignment.submission_score }}分)</span>
                                {% endif %}
                            {% endif %}
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>

            <div class="files-panel">
                <div class="panel-content">
                    <div class="content-section">
                        <div class="header-actions" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                            <h2>课程资源</h2>
                            <div class="actions">
                                {% if user_info.role == 'teacher' %}
                                <form id="uploadForm" style="display: inline-block; margin-right: 10px;">
                                    <input type="file" id="fileInput" style="display: none;" multiple>
                                    <button type="button" class="button primary-button" onclick="document.getElementById('fileInput').click()">
                                        上传文件
                                    </button>
                                </form>
                                {% endif %}
                                <button type="button" class="button secondary-button" onclick="refreshFiles()">
                                    刷新列表
                                </button>
                            </div>
                        </div>

                        <table>
                            <thead>
                                <tr>
                                    <th>文件名</th>
                                    <th>大小</th>
                                    {% if user_info.role == 'teacher' %}
                                    <th>操作</th>
                                    {% endif %}
                                </tr>
                            </thead>
                            <tbody id="file-list-body">
                                {% for file in shared_files %}
                                <tr>
                                    <td><a href="/download/course_file/{{ file.id }}">{{ file.name }}</a></td>
                                    <td>{{ file.size }}</td>
                                    {% if user_info.role == 'teacher' %}
                                    <td>
                                        <button class="button danger-button" onclick="deleteFile({{ classroom.course_id }}, {{ file.id }})">
                                            删除
                                        </button>
                                    </td>
                                    {% endif %}
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>

        <div class="panel chat-panel">
            <div class="panel-header">
                <h2>课堂研讨室</h2>
            </div>
            <div class="chat-messages" id="chat-messages">
                </div>
            <div class="chat-input">
                <input type="text" id="chat-input" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
                <button onclick="sendMessage()">发送</button>
            </div>
        </div>
    </div>

    {% if user_info.role == 'teacher' %}
    <div id="assignment-modal" class="modal-overlay" style="display: none;"> <div class="modal-content">
            <h2>作业编辑器</h2>
            <input type="hidden" id="assignment-id">
            <div>
                <label for="assignment-title">标题:</label>
                <input type="text" id="assignment-title">
            </div>
            <div>
                <label for="assignment-requirements">要求说明:</label>
                <textarea id="assignment-requirements"></textarea>
            </div>
            <div>
                <label for="assignment-rubric">评分标准:</label>
                <textarea id="assignment-rubric"></textarea>
            </div>
            <div>
                <label for="assignment-grading-mode">批改模式:</label>
                <select id="assignment-grading-mode">
                    <option value="manual">手动批改</option>
                    <option value="ai">AI辅助批改</option>
                </select>
            </div>
            <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                <button class="button secondary-button" onclick="closeAssignmentModal()">取消</button>
                <button class="button primary-button" onclick="saveAssignment()">保存</button>
            </div>
        </div>
    </div>
    {% endif %}

    <button id="ai-chat-fab" title="课堂AI助手">
        <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M12 3v.01M12 21v.01M3 12h.01M21 12h.01M5.64 5.64l.01.01M18.36 18.36l.01.01M5.64 18.36l.01.01M18.36 5.64l.01.01M12 8a4 4 0 1 1-8 0 4 4 0 0 1 8 0zM16 12a4 4 0 1 1 0-8 4 4 0 0 1 0 8z"/>
        </svg>
    </button>

    <div id="ai-chat-modal">
        <div class="ai-chat-container">
            <div class="ai-chat-header">
                <h3>课堂AI助手</h3>
                <div class="header-buttons">
                    <button id="ai-chat-btn-new" class="chat-btn" title="新对话">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14m-7-7h14"/></svg>
                    </button>
                    <button id="ai-chat-btn-fullscreen" class="chat-btn" title="全屏">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/>
                        </svg>
                    </button>
                    <button id="ai-chat-btn-close" class="chat-btn" title="关闭">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
                    </button>
                </div>
            </div>

            <div class="ai-chat-messages" id="ai-chat-messages-box">
                <div class="ai-chat-message system">
                    <div class="bubble">
                        你好！我是你的AI助教。你可以向我提问，或上传图片/截图。
                    </div>
                </div>
            </div>

            <div class="ai-chat-attachment-previews" id="ai-chat-previews">
                </div>

            <div class="ai-chat-input-area">
                <div class="input-row">
                    <input type="file" id="ai-chat-file-input" accept="image/*" multiple style="display: none;">

                    <!-- 左侧按钮组：深度思考 -->
                    <div class="left-buttons">
                        <button id="ai-deep-think-btn" class="chat-btn deep-think" title="深度思考">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l4 4-1.5 1.5-4-4v-.79l-.27-.27A6.516 6.516 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3"/>
                                <path d="m9 9 1.88 1.88"/>
                                <path d="M9 13.5V15l1.88-1.88"/>
                            </svg>
                        </button>
                    </div>

                    <!-- 中间：文本输入框 -->
                    <textarea id="ai-chat-textarea" placeholder="输入消息..." rows="1"></textarea>

                    <!-- 右侧按钮组：附件和发送 -->
                    <div class="right-buttons">
                        <button id="ai-chat-btn-attach" class="chat-btn attach" title="上传图片">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.49"/></svg>
                        </button>
                        <button id="ai-chat-btn-send" class="chat-btn send" title="发送">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
                        </button>
                    </div>
                </div>
            </div>

            <div class="resizer resizer-top"></div>
            <div class="resizer resizer-right"></div>
            <div class="resizer resizer-bottom"></div>
            <div class="resizer resizer-left"></div>
            <div class="resizer resizer-top-left"></div>
            <div class="resizer resizer-top-right"></div>
            <div class="resizer resizer-bottom-left"></div>
            <div class="resizer resizer-bottom-right"></div>

        </div>
    </div>

    <script src="/static/js/ai_chat_component.js"></script>

    <script>
        // --- 页面全局变量 ---
        const userInfo = {{ user_info | tojson }};
        const classroom = {{ classroom | tojson }};
        const classOfferingId = {{ classroom.id }};

        // --- 1. 课堂研讨室 (WebSocket) 逻辑 (保持不变) ---
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const ws = new WebSocket(`${wsProtocol}//${window.location.host}/ws/${classroom.id}`);

        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            if (data.type === 'chat') {
                appendChatMessage(data);
            } else if (data.type === 'system') {
                appendSystemMessage(data.message);
            } else if (data.type === 'history') {
                data.data.forEach(msg => {
                    if (msg.type === 'chat') appendChatMessage(msg);
                    else if (msg.type === 'system') appendSystemMessage(msg.message);
                });
            }
        };

        function appendChatMessage(msg) {
            const msgDiv = document.createElement('div');
            msgDiv.className = 'chat-message';
            msgDiv.innerHTML = `
                <span class="sender">${msg.sender}</span>
                <span class="time">${msg.timestamp}</span><br>
                <span class="message"></span>
            `;
            msgDiv.querySelector('.message').textContent = msg.message;
            const chatBox = document.getElementById('chat-messages');
            chatBox.appendChild(msgDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function appendSystemMessage(message) {
            const msgDiv = document.createElement('div');
            msgDiv.className = 'chat-message system';
            msgDiv.innerHTML = `<span class="message"></span>`;
            msgDiv.querySelector('.message').textContent = message;
            const chatBox = document.getElementById('chat-messages');
            chatBox.appendChild(msgDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function sendMessage() {
            const input = document.getElementById('chat-input');
            const message = input.value.trim();
            if (message && ws.readyState === WebSocket.OPEN) {
                ws.send(message);
                input.value = '';
            }
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        // --- 2. 作业模态框 (教师) 逻辑 (保持不变) ---
        {% if user_info.role == 'teacher' %}
        function openAssignmentModal() {
            document.getElementById('assignment-modal').style.display = 'flex';
            document.getElementById('assignment-id').value = '';
            document.getElementById('assignment-title').value = '';
            document.getElementById('assignment-requirements').value = '';
            document.getElementById('assignment-rubric').value = '';
            document.getElementById('assignment-grading-mode').value = 'manual';
        }

        function closeAssignmentModal() {
            document.getElementById('assignment-modal').style.display = 'none';
        }

        async function saveAssignment() {
            const id = document.getElementById('assignment-id').value;
            const data = {
                title: document.getElementById('assignment-title').value,
                requirements_md: document.getElementById('assignment-requirements').value,
                rubric_md: document.getElementById('assignment-rubric').value,
                grading_mode: document.getElementById('assignment-grading-mode').value,
                status: 'new'
            };

            try {
                const url = id ? `/api/assignments/${id}` : `/api/courses/${classroom.course_id}/assignments`;
                const response = await fetch(url, {
                    method: id ? 'PUT' : 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    location.reload();
                } else {
                    const error = await response.json();
                    alert('保存失败: ' + error.detail);
                }
            } catch (e) {
                alert('保存失败: ' + e);
            }
        }
        {% endif %}


        // --- 3. 课程资源 (文件上传/删除/刷新) 逻辑 (保持不变) ---
        document.getElementById('fileInput')?.addEventListener('change', async function(e) {
            const files = e.target.files;
            if (!files.length) return;

            let hasError = false;
            for (const file of files) {
                const formData = new FormData();
                formData.append('file', file);
                formData.append('is_public', 'true');

                try {
                    const response = await fetch(`/api/courses/${classroom.course_id}/files/upload`, {
                        method: 'POST',
                        body: formData
                    });
                    if (!response.ok) throw new Error(await response.text());
                    const result = await response.json();
                    if (result.status === 'success') {
                        showMessage(`文件 "${file.name}" 上传成功！`);
                    }
                } catch (error) {
                    showMessage(`上传失败: ${error.message}`, 'error');
                    hasError = true;
                }
            }
            if (!hasError || files.length > 0) {
                 refreshFiles();
            }
        });

        async function deleteFile(courseId, fileId) {
            if (!confirm('确定要删除此文件吗?')) return;
            try {
                const response = await fetch(`/api/courses/${courseId}/files/${fileId}`, {
                    method: 'DELETE'
                });
                if (!response.ok) throw new Error(await response.text());
                const result = await response.json();
                if (result.status === 'success') {
                    showMessage('文件删除成功！');
                    refreshFiles();
                }
            } catch (error) {
                showMessage(`删除失败: ${error.message}`, 'error');
            }
        }

        async function refreshFiles() {
            const tableBody = document.getElementById('file-list-body');
            if (!tableBody) return;
            tableBody.innerHTML = '<tr><td colspan="3" style="text-align: center;">正在刷新...</td></tr>';
            try {
                const response = await fetch(`/api/courses/${classroom.id}/files`);
                if (!response.ok) throw new Error('获取文件列表失败。');
                const data = await response.json();
                tableBody.innerHTML = '';
                const colspan = data.is_teacher ? '3' : '2';
                if (data.files.length === 0) {
                    tableBody.innerHTML = `<tr><td colspan="${colspan}" style="text-align: center;">没有课程资源。</td></tr>`;
                    return;
                }
                const isTeacher = data.is_teacher;
                data.files.forEach(file => {
                    const tr = document.createElement('tr');
                    const tdName = document.createElement('td');
                    tdName.innerHTML = `<a href="/download/course_file/${file.id}">${file.file_name}</a>`;
                    tr.appendChild(tdName);
                    const tdSize = document.createElement('td');
                    tdSize.textContent = sizeFormat(file.file_size);
                    tr.appendChild(tdSize);
                    if (isTeacher) {
                        const tdAction = document.createElement('td');
                        tdAction.innerHTML = `
                            <button class="button danger-button" onclick="deleteFile(${classroom.course_id}, ${file.id})">
                                删除
                            </button>
                        `;
                        tr.appendChild(tdAction);
                    }
                    tableBody.appendChild(tr);
                });
            } catch (error) {
                console.error('刷新文件列表时出错:', error);
                const colspan = (userInfo.role === 'teacher') ? '3' : '2';
                tableBody.innerHTML = `<tr><td colspan="${colspan}" style="text-align: center; color: red;">加载文件列表失败！</td></tr>`;
            }
        }

        function sizeFormat(bytes) {
            const units = ['B', 'KB', 'MB', 'GB', 'TB'];
            let i = 0;
            while (bytes >= 1024 && i < units.length - 1) {
                bytes /= 1024;
                i++;
            }
            return `${bytes.toFixed(2)} ${units[i]}`;
        }

        // --- 4. 辅助函数 (showMessage) (保持不变) ---
        function showMessage(message, type = 'success') {
            const div = document.createElement('div');
            div.textContent = message;
            div.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 10px 20px;
                border-radius: 4px;
                background: ${type === 'success' ? '#4caf50' : '#f44336'};
                color: white;
                z-index: 9999;
                box-shadow: var(--shadow);
                animation: slideIn 0.3s ease;
            `;
            const styleSheet = document.createElement("style");
            styleSheet.type = "text/css";
            styleSheet.innerText = `@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }`;
            document.head.appendChild(styleSheet);
            document.body.appendChild(div);
            setTimeout(() => {
                div.remove();
                styleSheet.remove();
            }, 3000);
        }

        // --- 5. AI 聊天组件初始化 (修改) ---
        document.addEventListener('DOMContentLoaded', () => {
            // (所有 AI 聊天 JS 逻辑已移走)

            // *** 新增: 初始化 AI 组件 ***
            try {
                const aiChat = new AIChatComponent({
                    classOfferingId: classOfferingId
                });
                aiChat.init();
            } catch (e) {
                console.error("初始化 AI 助手失败:", e);
            }
        });
    </script>
</body>
</html>